//
//  CNImageBrowserToolViewHandler.m
//  CsdnPlus
//
//  Created by wxlan on 2019/8/20.
//  Copyright © 2019 CSDN. All rights reserved.
//

#import "CNBBSBrowserToolViewHandler.h"
#import "CNImageBrowserSheetView.h"
#import <CNBaseTool/CNCategoryHeader.h>


@interface CNBBSBrowserToolViewHandler ()
@property (nonatomic, strong) UILabel *indexLabel;
@property (nonatomic, strong) CNImageBrowserSheetView *sheetView;
@property (nonatomic, strong) YBIBSheetAction *saveAction;
@property (nonatomic, copy) NSString *qrCodeUrl;
@end

@implementation CNBBSBrowserToolViewHandler
#pragma mark - <YBIBToolViewHandler>

@synthesize yb_containerView = _yb_containerView;
@synthesize yb_currentData = _yb_currentData;
@synthesize yb_containerSize = _yb_containerSize;
@synthesize yb_currentPage = _yb_currentPage;
@synthesize yb_totalPage = _yb_totalPage;
@synthesize yb_currentOrientation = _yb_currentOrientation;

- (void)yb_containerViewIsReadied {
    [self.yb_containerView addSubview:self.indexLabel];
    
    CGSize size = self.yb_containerSize(self.yb_currentOrientation());
    self.indexLabel.center = CGPointMake(size.width / 2.0, size.height - 80);
}
- (void)yb_respondsToLongPress {
    [self showSheetView];
}
- (void)yb_hide:(BOOL)hide {
    self.indexLabel.hidden = hide;
    [self.sheetView hideWithAnimation:NO];

}
- (void)yb_orientationWillChangeWithExpectOrientation:(UIDeviceOrientation)orientation {
    [self.sheetView hideWithAnimation:NO];
}
- (void)yb_pageChanged {
    if (self.yb_totalPage() <= 1) {
        self.indexLabel.hidden = YES;
    } else {
        self.indexLabel.hidden  = NO;
        self.indexLabel.text = [NSString stringWithFormat:@"%ld / %ld", self.yb_currentPage() + 1, self.yb_totalPage()];
    }


    [self updateViewIndexLabelSize];
}

- (void)yb_orientationChangeAnimationWithExpectOrientation:(UIDeviceOrientation)orientation {
    // 旋转的效果自行处理了
}

#pragma mark - private
- (void)showSheetView {
    if ([self.yb_currentData() respondsToSelector:@selector(yb_saveToPhotoAlbum)]) {
        if (![self.sheetView.actions containsObject:self.saveAction]) {
            [self.sheetView.actions addObject:self.saveAction];
        }
    } else {
        [self.sheetView.actions removeObject:self.saveAction];
    }
    
    UIImageView *imageView = [[UIImageView alloc]init];
    YBIBImageData *imageData = (YBIBImageData *)self.yb_currentData();
    @weakify(self);
    [imageView sd_setImageWithURL:imageData.imageURL completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        @strongify(self);
        if (!error && image) {
            CIImage *ciImage = [[CIImage alloc] initWithCGImage:image.CGImage options:nil];
            CIContext *ciContext = [CIContext contextWithOptions:@{kCIContextUseSoftwareRenderer : @(YES)}]; // 软件渲染
            CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:ciContext options:@{CIDetectorAccuracy : CIDetectorAccuracyHigh}];// 二维码识别
            NSArray *features = [detector featuresInImage:ciImage];
            
        }
        [self.sheetView showToView:self.yb_containerView orientation:self.yb_currentOrientation()];
    }];
}
- (void)updateViewIndexLabelSize {
    CGSize size = self.indexLabel.intrinsicContentSize;
    self.indexLabel.bounds = (CGRect){CGPointZero, CGSizeMake(size.width + 15, size.height)};
}

- (UILabel *)indexLabel {
    if (!_indexLabel) {
        _indexLabel = [[UILabel alloc]init];
        _indexLabel.theme_textColor = cellDesTitleTextColorPicker;
        _indexLabel.font = [UIFont systemFontOfSize:14];
        _indexLabel.textAlignment = NSTextAlignmentCenter;
        _indexLabel.adjustsFontSizeToFitWidth = YES;
    }
    return _indexLabel;
}
#pragma mark - getters

- (CNImageBrowserSheetView *)sheetView {
    if (!_sheetView) {
        _sheetView = [CNImageBrowserSheetView new];
        __weak typeof(self) wSelf = self;
        [_sheetView setCurrentdata:^id<YBIBDataProtocol>{
            __strong typeof(wSelf) self = wSelf;
            if (!self) return nil;
            return self.yb_currentData();
        }];
    }
    return _sheetView;
}

- (YBIBSheetAction *)saveAction {
    if (!_saveAction) {
        __weak typeof(self) wSelf = self;
        _saveAction = [YBIBSheetAction actionWithName:@"保存图片" action:^(id<YBIBDataProtocol> data) {
            __strong typeof(wSelf) self = wSelf;
            if (!self) return;
            if ([data respondsToSelector:@selector(yb_saveToPhotoAlbum)]) {
                [data yb_saveToPhotoAlbum];
            }
            [self.sheetView hideWithAnimation:YES];
        }];
    }
    return _saveAction;
}

#pragma mark - 获取导航控制器

//获取当前屏幕显示的viewcontroller
- (UIViewController *)currentViewController {

    UIViewController *result = nil;

    UIViewController *rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;

    do {
        if ([rootVC isKindOfClass:[UINavigationController class]]) {
            UINavigationController *navi = (UINavigationController *)rootVC;
            UIViewController *vc = [navi.viewControllers lastObject];
            result = vc;
            rootVC = vc.presentedViewController;
            continue;
        } else if([rootVC isKindOfClass:[UITabBarController class]]) {
            UITabBarController *tab = (UITabBarController *)rootVC;
            result = tab;
            rootVC = [tab.viewControllers objectAtIndex:tab.selectedIndex];
            continue;
        } else if([rootVC isKindOfClass:[UIViewController class]]) {
            result = rootVC;
            rootVC = nil;
        }
    } while (rootVC != nil);

    return result;
}

@end
